import Vue from 'vue'
import Vuex from 'vuex'
import Axios from 'axios'
Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    // 所有的任务列表
    list: [],
    // 文本框的内容
    inputValue: 'aaa',
    nextId: 6,
    viewKey: 'all'
  },
  mutations: {
    initList (state, list) {
      state.list = list
      console.log(state.list)
    },
    setInputValue (state, val) {
      state.inputValue = val
    },
    addItem (state) {
      const obj = {
        id: state.nextId,
        info: state.inputValue,
        done: false
      }
      state.list.push(obj)
      state.nextId++
      state.inputValue = ''
      console.log(state.list)
    },
    keyChange (state, key) {
      state.viewKey = key
    },
    clearDoneState (state) {
      state.list = state.list.filter(x => x.done === false)
    },
    deleteThis (state, id) {
      const dId = state.list.findIndex(x => x.id === id)
      state.list.splice(dId, 1)
    },
    // 监听checkbox改变事件
    checkStatusChanged (state, params) {
      const i = state.list.findIndex(x => x.id === params.id)
      if (i !== -1) {
        state.list[i].done = params.checked
      }
    }
  },
  actions: {
    getList (context) {
      Axios.get('/list.json').then(({
        data
      }) => {
        // console.log(data)
        context.commit('initList', data)
      })
    }
  },
  getters: {
    undoneLength (state) {
      return state.list.filter(x => x.done === false).length
    },
    infoList (state) {
      if (state.viewKey === 'all') {
        return state.list
      }
      if (state.viewKey === 'undone') {
        return state.list.filter(x => x.done === false)
      }
      if (state.viewKey === 'done') {
        return state.list.filter(x => x.done === true)
      }
      return state.list
    }
  },
  modules: {}
})
